import {Component, OnInit, ViewChild} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {DeviceService} from './device.service';
import {DeviceEditComponent} from './device-edit/device-edit.component';
import { DeviceScrapComponent } from "./device-scrap/device-scrap.component";

@Component({
  selector: 'app-device-list',
  templateUrl: './device-list.component.html',
  styles: []
})
export class DeviceListComponent implements OnInit {

  loading = false;

  // 设备组数据
  deviceGroups = [];

  // 分页参数
  pageData = {page: 0, size: 10};
  // 查询条件
  searchBeans = [{
    attributeName: 'code',
    searchType: 'LIKE',
    attributeValue: ''
  }, {
    attributeName: 'name',
    searchType: 'LIKE',
    attributeValue: ''
  }, {
    attributeName: 'scrapped',
    searchType: 'EQ',
    dataType: 'BOOLEAN',
    attributeValue: false
  }];

  // 设备编辑
  @ViewChild('deviceEditComponent', {static: false})
  public deviceEditComponent: DeviceEditComponent;
  // 设备报废
  @ViewChild('deviceScrapComponent', {static: false})
  public deviceScrapComponent: DeviceScrapComponent;

  constructor(private deviceGroupSrv: DeviceService,
              private msgSrv: NzMessageService,) {
  }

  ngOnInit(): void {
    this.loadListData();
  }

  delete(id?) {
    this.loading = true;
    this.deviceGroupSrv.delete(id).subscribe((res) => {
      this.loading = false;
      if (res.code === 1) {
        this.msgSrv.success('删除完成');
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  // 设备报废
  scrap(data){
    this.deviceScrapComponent.edit(data);
  }

  onSmt() {
    this.loadListData();
  }

  cancel() {
    this.msgSrv.success('已取消');
  }

  open(){
    this.deviceEditComponent.open();
  }

  openEdit(record ?: any): void {
    this.deviceEditComponent.edit(record);
  }

  /**
   * 清除查询参数
   */
  clearParam() {

    this.searchBeans.forEach((item) => {
      item.attributeValue = '';
    });
  }

  /**
   * 加载列表数据
   */
  loadListData() {

    this.loading = true;

    const searchData = {
      page: this.pageData.page,
      size: this.pageData.size,
      searchFilter: {
        searchBeans: this.searchBeans
      }
    };

    this.deviceGroupSrv.findPage(searchData).subscribe((res) => {

      this.loading = false;

      if (res.code === 1) {
        this.deviceGroups = res.data.content;
      } else {
        this.msgSrv.error(res.message);
      }

    });
  }

  _onReuseInit() {
    this.loadListData();
  }
}
